package org.yasukusury.crawler.helper;

import org.apache.http.client.utils.URIBuilder;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.yasukusury.crawler.dao.Copy;
import org.yasukusury.crawler.dao.List;
import org.yasukusury.crawler.variation.AmazonUSCrawler;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CountDownLatch;

import static org.yasukusury.crawler.helper.Utils.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Y
 * Date: 2017-11-15
 * Time: 13:14
 */
public class PageDistributor implements Callable<Result> {
    private String asin;
    private Result result;
    private ConcurrentLinkedDeque<Copy> copies;
    private URI uri;

    public PageDistributor(String asin) {
        this.asin = asin;
    }

    private void start() throws IOException, InterruptedException {
        fillList();
        int count = result.getList().getTotalCount();
        Integer pagenum = 1;
        HashSet<Thread> subSet = new HashSet<>();
        CountDownLatch cdl = new CountDownLatch(count / 200 + 1);
        copies = new ConcurrentLinkedDeque<>();
        while (count > 0) {
            count -= 200;
            int distribution = count < 0 ? count + 200 : 200;
            Thread sub = new Thread(new AmazonUSCrawler(asin, copies, pagenum, distribution, cdl));
            subSet.add(sub);
            pagenum += 20;
        }
        for (Thread t : subSet) {
            t.start();
        }
        cdl.await();
        result.setCopies(copies);
    }

    private void fillList() throws IOException {
        Document doc = null;
        try {
            urlPrase(asin);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            System.out.println("URI解析失败");
        }

        doc = httpClientGet(uri, asin, 1);
        if (doc == null)
            exit(true);
        Element title = doc.select("h1 a[data-hook=product-link]").first();
        Element reviews = doc.getElementById("cm_cr-review_list");
        if (reviews == null)
            exit(true);
        Element count = reviews.child(0).child(0);
        Element format = reviews.child(0).child(2);

        String titleText = getPlainText(title);
        String formatText = getPlainText(format);
        Integer countInteger = Integer.valueOf(getPlainText(count).split(" ")[3].replaceAll(",", ""));

        result = new Result();
        List list = new List();
        list.setAsin(asin);
        list.setTitle(titleText);
        list.setFormat(formatText);
        list.setTotalCount(countInteger);
        result.setList(list);
    }

    private void exit(boolean except) throws IOException {
        if (except)
            System.out.println(String.format("ASIN : %s 评论链接连接失败", asin));
        throw new IOException();
    }

    private void urlPrase(String asin) throws URISyntaxException {
        uri = new URIBuilder()
                .setScheme("https")
                .setHost("www.amazon.com")
                .setPath("/product-reviews/" + asin)
                .setParameter(param[0], param[1])
                .setParameter(param[2], param[3])
                .setParameter(param[4], param[5])
                .setParameter(param[6], "1")
                .build();
    }

    @Override
    public Result call() {
        try {
            start();
        } catch (IOException e) {
            System.out.println(String.format("商品 %s 爬取信息失败", asin));
            return null;
        } catch (InterruptedException e) {
            System.out.println(String.format("商品 %s 多线程失败", asin));
            return null;
        }
        return result;
    }

}
